package com.kokos.backingbeans;


import java.io.Serializable;

import javax.annotation.Resource;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import org.apache.log4j.Logger;

import com.kokos.dao.user.AccountDAOFacadeLocal;
import com.kokos.dao.user.UserGroupDAOFacadeLocal;
import com.kokos.dao.user.UserInfoDAOFacadeLocal;
import com.kokos.entities.user.Account;
import com.kokos.entities.user.UserGroup;
import com.kokos.entities.user.UserInfo;

@RequestScoped
@ManagedBean(name = "registration")
public class RegistrationBean implements Serializable{
	
	private static final long serialVersionUID = -7598428581923845476L;
	
	private final Logger LOGGER = Logger.getLogger(getClass().getName());
	
	private static final String MAIL_SUBJECT = "New kokos-app user";
	
	private Account account;
	private UserGroup group;
	private UserInfo info;
	
	@EJB(name="AccountDAO")
	UserGroupDAOFacadeLocal userGroupDAOFacade;
	@EJB(name="UserGroupDAO")
	AccountDAOFacadeLocal accountDAOFacade;
	@EJB(name="UserInfoDAO")
	UserInfoDAOFacadeLocal userInfoDAOFacade;
	
	@Resource(name="mail/kokosMail")
	private Session session;
	
	public RegistrationBean() {
		account = new Account();
		group = new UserGroup();
		info = new UserInfo();
	}
	
    public Account getAccount() {
		return account;
	}

	public void setAccount(Account account) {
		this.account = account;
	}

	public UserGroup getGroup() {
		return group;
	}
	
	public void setGroup(UserGroup group) {
		this.group = group;
	}
	
	public UserInfo getInfo() {
		return info;
	}
	
	public void setInfo(UserInfo info) {
		this.info = info;
	}
	
	public String registerUser() {
		
		group.setUserGroup("user");
		account.setUserGroup(group);
		
		account.setUserLogin(group.getUserLogin());
		account.setUserInfo(info);
		
		sendEmail();
		
		userGroupDAOFacade.save(group);
		userInfoDAOFacade.save(info);
		accountDAOFacade.save(account);
		
		return "index";
		
	}
	
	private void sendEmail() {
		try {
			Message msg = new MimeMessage(session);
			msg.setRecipient(Message.RecipientType.TO, new InternetAddress(info.getUserMail()));
			msg.setSubject(MAIL_SUBJECT);
			msg.setText("Congrats, bro! You joined kokos-app with login: " + account.getUserLogin());
			Transport.send(msg);
		} catch (AddressException e) {
			LOGGER.error( "Invalid mail: " + info.getUserMail());
			LOGGER.error(e);
		} catch (MessagingException e) {
			LOGGER.error(e);
		}
	}

}
